var app = getApp();
import {
  api,
  util,
  dialog,
  forms,
  storage
} from '../../../js/util'
import {
  router
} from '../../../js/router';
import {
  fastorder,
  order,
  cart
} from "../../../js/modules/order.js"
import {
  detail,
  mall,
  list,
  scant,
  specModel
} from "../../../js/modules/mall.js";
import {
  activities
} from "../../../js/modules/market.js";

import authorize from '../../../js/modules/authorize.js'
import { deepClone, deepMerge, getSystemInfoSync, isEmpty } from '../../../js/newUtil';
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      this.outofstock = this.selectComponent("#outofstock");
      this.stockdistribution = this.selectComponent("#stockdistribution");
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的属性列表
   */
  properties: {
    item:{
        type:Object,
        value:{}
      },
    quantityDigits:{
      type:Number,
      value:0
    },
    priceDigits:{
      type:Number,
      value:2
    },
    decimalDigits: {
      type: Number,
      value: 2
    },
    isScanty:{
      type:Boolean,
      value:false
    },
    hasMaket: {
      value: false,
      type: Boolean
    },
    //规格展示样式
    spectStyle:{
      type:Number,
      value:0
    },
    areaCode:{
      type:String,
      value:""
    },
    picX:{
      type:Number,
      value:200
    },
    picY: {
      type: Number,
      value: 200
    },
    GoodsUnitDisplayMode:{
      type: Number,
      value: 0
    },
    mainColor:String,
    Currency:String,
    NoLoginShowPrice:Boolean,
    isLogin:Boolean,
    CartName:String,
    listState:Boolean,
    ShowVendorName:Boolean,
    FrontShowStockDetail:Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    chooseProduct: [],
    goodSpecific: [],
    chooseGoodsUnits: [],
    selectSpectValues: [],//选择的规格值
    goodsIndex: -1,//当前选中货口索引
    specifictions: [], //规格信息
    contents_code:[],
    current_swiper_index:0,
    enableSKUTranslated:false,
    specObj:{},//最大值--最小值
    showModalImg:false,
    imgsList:[],
    idx:0,//查看大图索引
    goodGroupList: [], // 商品组合更多列表
    groupProductInfo: {}, // 商品组的商品信息
    isShowGroupProduct: false, // 是否为商品组的商品
    productSpecHeight: 800, // 商品弹窗滚动区规格高度
    BatchJoinCartUnits: [], // 商品批量加购时的单位列表
    MinSalesPrice: 0, // 范围价格最小价格
    MaxSalesPrice: 0, // 范围价格最大价格
    priceRangeUnit: '', // 范围价格时的单位
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /*
      *弹出多规格层
     */
    onShowGoodsModal(e,parent_obj){
      let that=this;
      let product = this.data.item;
      let {
        spectStyle,
        areaCode,
        hasMaket,
        isShowGroupProduct,
        groupProductInfo
      } = this.data;
      if (isShowGroupProduct) {
        product = groupProductInfo
      }
      let param = {
        productId: product.ProductId || '',
        promotions: product.Promotions || {},
        spectStyle: spectStyle,
        areaCode: areaCode,
        current_swiper_index:0
      }
      let isPanic = false
      if (!isEmpty(product.isPanic)) {
        isPanic = product.isPanic
      }
      detail.loadSpecific(param, (goodSpecific, specifictions, units, content)=> {
        that.setData({
          DisplayBatchJoinCartArea: content.DisplayBatchJoinCartArea,
          DisplaySpecHorizontalSwitchArea: content.DisplaySpecHorizontalSwitchArea,
          goodGroupList: content.GroupInfo || [],
          BatchJoinCartUnits: content.BatchJoinCartUnits || [],
        })
        if (isShowGroupProduct) {
          let good = that.addActivityInfo(product, content)
          product = good
        }
        //促销商品不显示特价
        if (hasMaket) {
          isPanic = false
        }
        detail.decorate_specific(goodSpecific, product.PanicGoods, isPanic);
        //判断是否全部规格都是特价
        let isAllPanic = true;
        goodSpecific.map((g) => {
          if(!g.isPanic){
            isAllPanic = false
          }
        })
        product.isAllPanic = isAllPanic;
        //默认单位
        goodSpecific.map((g)=>{
          let units = g.AuxiliaryUnits||[];
          if (units.length > 0) {
            for (let j = 0; j < units.length; j++) {
              if (g.DefaultUnit == units[j].Name) {
                g.ZIndex = j;
                break;
              }
            }
          }
        })
        //价格
        goodSpecific.map((g)=>{
          let units = g.AuxiliaryUnits||[];
          that.unitList(units,g.UnitPrices,g.CartCount,g)
          g.show = false;
        })
        if (spectStyle == 1) {
          specModel.setGoodsIndex(specifictions, goodSpecific, -1, (specDecorate) => {
            //初始化选择框
            specModel.checkedSpecValueEvent(specifictions);
            if (product.PanicBuy && !hasMaket){
              product.PanicBuy.map((p) => {
                p.marketGoods.map((m) => {
                  goodSpecific.map((g) => {
                    if (g.isPanic && g.GoodsId == m.GoodsId) {
                        g.market = [p]
                    }
                  })
                })                

              })
            }
            content.MinSalesPrice = (content.MinSalesPrice).toFixed(2)
            content.MaxSalesPrice = (content.MaxSalesPrice).toFixed(2)
            that.setData({
              goodsIndex: specDecorate.goodsIndex,
              chooseProduct: [product],
              goodSpecific: goodSpecific,
              chooseGoodsUnits: units|| [],
              isPanic: isPanic,
              specifictions: specifictions,
              enableSKUTranslated: [product][0].EnableSKUTranslated==1?true:false,
              specObj:content
            });
          })
        }
        else{
          that.setData({
            goodsIndex: -1,
            chooseProduct: [product],
            goodSpecific: goodSpecific,
            chooseGoodsUnits: units || [],
            isPanic: isPanic,
            specifictions: specifictions,
            enableSKUTranslated: [product][0].EnableSKUTranslated==1?true:false
          });
        }
        let priceDigits = that.data.priceDigits
        let MinSalesPrice = content.MinSalesPrice || 0
        let MaxSalesPrice = content.MaxSalesPrice || 0
        let DefaultUnit = content.DefaultUnit || ''
        that.setData({
          MaxSalesPrice,
          MinSalesPrice,
          priceRangeUnit: DefaultUnit
        })
        that.setProductSpecHeight()
        dialog.showModal(that, 'showModalStatus')
      });
      
    },
    unitList(AuxiliaryUnits,UnitPrices,CartCount,goodlist){
      let { quantityDigits } = this.data;
      for(var i=0;i<AuxiliaryUnits.length;i++){
        var item = AuxiliaryUnits[i];
        var t = detail.parseRule(UnitPrices, item.Translated, item.Qty || 0, false);
        if(t.has){
          item.price = t.price;
          if(t.integral){
            item.integral = t.integral;
          }
        }
        var otherAuxiliaryUnits = AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
        var otherUnitQuantity = 0;
        if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
            otherAuxiliaryUnits.map((child, idx) => {
                if (child.Qty!=undefined&&child.Qty>0) {
                    otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
                }
            });
        }
        item.BuyLowerLimit = goodlist.SBuyLowerLimit > 0 && goodlist.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
        item.BuyUpperLimit = goodlist.SBuyUpperLimit > 0 && goodlist.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
        item.Stock = goodlist.SStock > 0 && goodlist.SStock > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SStock - otherUnitQuantity, quantityDigits) : 0;
        item.IsSingle = goodlist.IsSingle;
        item.DefaultUnit = item.Name;
        item.ZeroStockBuy = goodlist.ZeroStockBuy;
        item.SpecValue = goodlist.SpecValue;
        item.ProductId = goodlist.ProductId;
        item.DiscountId = goodlist.DiscountId;
        item.DiscountType = goodlist.DiscountType;
        AuxiliaryUnits[i] = item;
        if(this.data.GoodsUnitDisplayMode == 0&&item.Translated == (goodlist.Translated||goodlist.Radix)){
          goodlist.BuyLowerLimit = item.BuyLowerLimit;
          goodlist.BuyUpperLimit = item.BuyUpperLimit;
          goodlist.Stock = item.Stock;
        }
      }
    },
    /**
     * 根据条码搜索
     */
    onSearchProductCode(e){
      var that=this;
      mall.get_product_info_by_code(that.data.code, that.data.areaCode,(res)=> {
        if(!res.Success){
          util.tips("很抱歉！"+res.Message);
          return;
        }
        //把活动信息附加到商品对象     
        activities.loadProductActivities(res.Content,false,0,that.data.areaCode,function (gres) {
          gres.map((item)=>{
            item.panicShow = true;
            item.goodsIndex=-1;
            item.MaxSalesPrice = (item.MaxSalesPrice).toFixed(2)
            item.MinSalesPrice = (item.MinSalesPrice).toFixed(2)
            item.DefaultUnit = item.Goods[0].DefaultUnit;
            item.codeType=1;
            // item.scanCode=0;
            item.Goods.map((g) => {
              detail.decoratePromotion(g, item.Promotions);
            })
            let isPanic = (item.isPanic == undefined) ? false : item.isPanic;
            if(item.PanicBuy){
              detail.decorate_specific(item.Goods, item.PanicGoods, isPanic);
            }
            //判断是否全部规格都是特价
            let isAllPanic = true;
            item.Goods.map((g) => {
              if(!g.isPanic){
                isAllPanic = false
              }
            })
            item.isAllPanic = isAllPanic; //默认单位
            item.Goods.map((g)=>{
              let units = g.AuxiliaryUnits||[];
              if (units.length > 0) {
                for (let j = 0; j < units.length; j++) {
                  if (g.DefaultUnit == units[j].Name) {
                    g.ZIndex = j;
                    break;
                  }
                }
              }
            })
            //价格
            item.Goods.map((g)=>{
              let units = g.AuxiliaryUnits||[];
              that.unitList(units,g.UnitPrices,g.CartCount,g)
              g.show = false;
            })
            if (that.data.spectStyle == 1) {
              specModel.setGoodsIndex(item.Specifiction, item.Goods, -1, (specDecorate) => {
                if (specDecorate.goodsIndex != -1) {
                  item.goodsIndex = specDecorate.goodsIndex;
                }
                //初始化选择框
                specModel.checkedSpecValueEvent(item.Specifiction);
              })
            }
          })
          that.setData({
            search_code: true,
            current_swiper_index: 0,
            contents_code: gres,
            specObj: gres[0],
            goodSpecific: gres[0].Goods
          })
        });
        dialog.showModal(that, 'showModalStatus')
      });
    },
    onSwithItem(e){
      let current_swiper_index = e.detail.current;
      let contents = this.data.contents_code;
      let content = contents[current_swiper_index];
      let isPanic = (content.Panicbuy != undefined && content.Panicbuy.length > 0) ? true : false;
      if (isPanic) {
        content.PanicGoods = content.Panicbuy[0].PanicGoods;
      }
      detail.decorate_specific(content.Goods, content.PanicGoods, isPanic);
      content.isPanic = isPanic;
      let key = "contents_code[" + current_swiper_index + "]";
      this.setData({
        contents_code: contents,
        current_swiper_index: current_swiper_index,
        goodSpecific: content.Goods
      });
    },
    onGoodsChangeEvent(e){
      let { search_code, current_swiper_index}=this.data;
      let { product, goods, goodsIndex, specifictions } = e.detail
      if (search_code){
        let key= "contents_code[" + current_swiper_index + "]";
        product.Goods[goodsIndex] = goods;
        product.goodsIndex = goodsIndex;
        if (specifictions){
          product.Specifiction = specifictions;
        }
        this.setData({
          [key]: product,
          goodsIndex: goodsIndex
        })
      }
      else{
        if(goodsIndex != -1){
          this.data.goodSpecific[goodsIndex] = goods;
          let key="goodSpecific["+goodsIndex+"]";
          this.setData({
            [key]:goods,
            goodsIndex: goodsIndex,
            product: product
          })
        }
        this.setData({goodsIndex:goodsIndex})
      }
    },
    /**
     * 组合列表模式时，批量修改商品规格数量/单位
     */
    onGoodsChangeMultipleEvent(e) {
      var that = this
      let {
        product,
        goodSpecific,
        lastItemIndex,
        specifictions
      } = e.detail
      let {
        search_code,
        current_swiper_index
      } = this.data
      if (search_code){
        let key= "contents_code[" + current_swiper_index + "]";
        product.Goods = goodSpecific;
        product.goodsIndex = lastItemIndex;
        if (specifictions){
          product.Specifiction = specifictions;
        }
        this.setData({
          [key]: product,
          goodsIndex: lastItemIndex
        })
      }
      else{
        if(lastItemIndex != -1){
          this.setData({
            goodSpecific: goodSpecific,
            goodsIndex: lastItemIndex,
            product: product
          })
        }
        this.setData({goodsIndex:lastItemIndex})
      }
    },
    packBatchAddCart(e){
      let that=this;
      let { current_swiper_index}=this.data;
      this.selectComponent("#productSpec" + current_swiper_index).onAddCarEvent((product)=>{
        if (typeof (that.data.addCompleted) == "function") {
          util.success("加入成功！",function(){
            that.data.addCompleted(product);
          },600);

        }
        that.hideModal();
      });
    },
    buyMultiNow(e){
      let that=this;
      let { current_swiper_index } = this.data;
      this.selectComponent("#productSpec" + current_swiper_index).onBuyEvent(()=>{
        that.hideModal();
      });
    },
    hideModal: function () {
      this.setData({
        search_code:false,
        groupProductInfo: {}, // 商品组的商品信息
        isShowGroupProduct: false, // 是否为商品组的商品
      })
      dialog.hideModal(this, 'showModalStatus')
    },
    /**
     * 促销活动跳转
     */
    onSkipDetail(e) {
      var that = this;
      var id = e.currentTarget.dataset.id;
      router.navigate({
        path: "promotionDetail",
        params:{
          id:id
        }
      })
    },
    /**
     * 显示缺货登记
     */
    onShowScantyEvent: function (e) {
      var that=this;
      var goods=e.detail;
      that.outofstock.setData({
        scantyProduct: goods,
      })
      that.outofstock.openScanyDialog(e);
    },
    /**
     * 显示库存分布
     */
    showStockDistribution(e) {
      var goods = e.detail;
      this.stockdistribution.setData({
        product: goods,
        isGoodsStock: true
      })
      this.stockdistribution.showStockModal(e);
    },
    preventTouchMove() {

    },
    onClickImage:function(e){
      var { imgDomain, goodSpecific, goodsIndex } = this.data;
      var imgsList = [];
      goodSpecific.map((g)=>{
        imgsList.push({MarkSrc:imgDomain+(g.GoodsDefaultPic||g.DefaultPic),name:g.SpecValue});
      })
      this.setData({
        showModalImg:true,
        imgsList:imgsList,
        idx:goodsIndex<0?0:goodsIndex
      })
    },
    lookImg:function(e){
      var list = e.detail.imgsList;
      var index = e.detail.index;
      this.setData({
        showModalImg:true,
        imgsList:list,
        idx:index
      })
      // console.log(e);
    },
    closeImg(){
      this.setData({
        showModalImg:false
      })
    },
    /**
     * 点击商品组/切换商品信息
     * @param {*} e 
     */
    changeProductByGroup (e) {
      let id = e.detail.id
      let item = this.data.item
      let groupProductInfo = {}
      let isShowGroupProduct = false
      if (item.ProductId != id) {
        groupProductInfo = {
          ProductId: id
        }
        isShowGroupProduct = true
      }
      this.setData({
        groupProductInfo,
        isShowGroupProduct
      })
      this.onShowGoodsModal(e)
    },
    /**
     * 调整商品数据，添加活动信息；同market.js中的loadProductActivities方法结果处理类似
     * @param {*} product 商品id数据
     * @param {*} content 接口返回的规格等数据
     */
    addActivityInfo(product, content) {
      let that = this
      let hasMaket = this.data.hasMaket
      let good = deepMerge(product, content)
      // 调整数据格式，调用公用方法去解析活动数据
      let FKFlag = app.dns.proprietor || ''
      let FKId = app.dns.proprietorId || ''
      let keyword = `${FKFlag}_${FKId}` // 其实任意值都行，为了让数据格式改为和方法需要的一致添加的
      let markets = {
        gifts: {
          [keyword]: content.Gifts || []
        },
        panics: {
          [keyword]: hasMaket == false ? [] : content.PanicBuy
        },
        promotions: {
          [keyword]: content.PromotRule || []
        }
      }
      let args = {
        isList: false
      }
      let productMarkets = activities.computeMarkets(markets, args, good.ProductId, content.AuxUnit || '', 0, content.Unit, content.DefaultUnit)
      good.loadcomplate = 1;
      good.DiscountId = 0;
      good.DiscountType = 0;
      good.linkParam = "ptype=0&id=" + good.ProductId + "&sid=" + good.SupplierId + "&productId=" + good.ProductId;
      good.pageType = 0;
      good.Promotions = [];
      good.Gift = [];
      good.PanicBuy = [];
      good.Label = [];
      // 此处的活动数据都是该商品的，所以需要全部都去添加
      for (let i in productMarkets) {
        let productMarket = productMarkets[i]
        if (productMarket == undefined) continue
        productMarket.markets.reverse().map((item) => {
          good = activities.signProduct(good, item)
        })
      }
      var market = [];
      var label = [];
      let promotionsLabel = [] // 显示的促销label
      let firstLabelIndex = -1 // 如果为组合促销，那么其中最先有当前商品的index
      if (good.isGroup) {
        market.push("拼团");
        var groups = good.Group;
        activities.stockSale(good, groups, 1)
      } else if (good.isPresale) {
        market.push("预售");
        var groups = good.Groupbuy;
        activities.stockSale(good, groups, 2)
      } else if (good.isPanic) {
        market.push("特价");
        var groups = good.PanicBuy;
        activities.stockSale(good, groups, 3)
      } else if (good.isPromotions) {
        good.Promotions.map((item, index) => {
          // label中有单品促销时，直接取单品促销
          if (item.productIds == good.ProductId) {
            promotionsLabel = [item]
          } else {
            // 判断是否在组合促销内
            let ids = item.productIds || ''
            ids = ids.split(',')
            let i = ids.findIndex((productId) => {
              return productId == good.ProductId
            })
            if (i != -1 && firstLabelIndex == -1) {
              firstLabelIndex = index
            }
          }
          if (good.IsSingle === 1) {
            label.push(good.Promotions[0].label)
            market.push(good.Promotions[0].name)
          } else {
            label.push(good.Promotions.length > 0 ? good.Promotions[good.Promotions.length - 1].label : '')
            market.push(good.Promotions.length > 0 ? good.Promotions[good.Promotions.length - 1].name : '')
          }
          // market.push(item.name)
          // label.push(item.label)
        });
        // 没有找到单品促销，并且有组合促销，则取组合促销的第一个
        if (promotionsLabel.length == 0) {
          if (firstLabelIndex != -1) {
            promotionsLabel.push(good.Promotions[firstLabelIndex])
          }
        }
        good.promotionsLabel = promotionsLabel
      }
      if (good.isGift && !good.isGroup && !good.isPresale) {
        market.push("赠品");
      }
      // if (good.isCoupon && !good.isGroup && !good.isPresale && !good.isPanic) {
      //   market.push("领券");
      // }
      let el = market.filter((item, index) => market.indexOf(item) === index);
      let els = label.filter((item, index) => label.indexOf(item) === index);
      good["market"] = el;
      good["Label"] = els;
      return good
    },
    setProductSpecHeight () {
      let goodSpecific = this.data.goodSpecific || []
      let length = goodSpecific.length
      let systemInfo = getSystemInfoSync()
      let height = 800
      if (length > 2) {
        height = systemInfo.rpxHeight * 0.8
      } else {
        height = systemInfo.rpxHeight * 0.6
      }
      if (height < 600) {
        height = 600
      }
      if (height + 100 > systemInfo.rpxHeight) {
        height = systemInfo.rpxHeight - 100
      }
      this.setData({
        productSpecHeight: height
      })
    }
  }
})
